<template>
	<view class="mainbgc">
		<header-top :messageInfo="{typeFlag:true,message:'货款交账',liner:false}">
			<view class="rightmsg" slot="rightmsg">
				<view class="rightmsg_content flexleft">
					<image class="img oneimg" src="../../../static/image/system/my2.png" mode="" @click="startPrint(132)">
					</image>
					<view class="ygtext" @click="sxshow=true">筛选</view>
				</view>
			</view>
		</header-top>
		<view class="bgcs" style="z-index: 12;">
			<view class="kuantiao ffffff">
				<view class="shoukuaant" @click="xiaoshousk(1)">
					<view class="box1  flexbetween">
						<view class="flexleft">
							<view class="xiaoshou">销售单</view>
							<view class="daijiao">待交{{dataAll.sale_total_num}}张</view>
						</view>
						<view class="flexright">
							<view class="qianshu margin_right">{{dataAll.sale_total_price}}</view>
							<view class="images">
								<image class="righticon2" src="../../../static/image/system/righticon2.png" mode=""></image>
							</view>
						</view>
					</view>
				</view>
				<view class="shoukuaant" @click="xiaoshousk(2)">
					<view class="box1  flexbetween">
						<view class="flexleft">
							<view class="xiaoshou">预收款</view>
							<view class="daijiao">待交{{dataAll.ysk_total_num}}张</view>
						</view>
						<view class="flexright">
							<view class="qianshu margin_right">{{dataAll.ysk_total_price}}</view>
							<view class="images">
								<image class="righticon2" src="../../../static/image/system/righticon2.png" mode=""></image>
							</view>
						</view>
						
					</view>
				</view>
				<!-- 客户结算 -->
				<view class="shoukuaant" @click="xiaoshousk(3)">
					<view class="box1  flexbetween">
						<view class="flexleft">
							<view class="xiaoshou">客户结算</view>
							<view class="daijiao">待交{{dataAll.sqk_total_num}}张</view>
						</view>
						<view class="flexright">
							<view class="qianshu margin_right">{{dataAll.sqk_total_price}}</view>
							<view class="images">
								<image class="righticon2" src="../../../static/image/system/righticon2.png" mode=""></image>
							</view>
						</view>
					</view>
				</view>
				<view class="shoukuaant">
					<view class="box1  flexbetween">
						<view class="flexleft">
							<view class="xiaoshou">合计</view>
							<view class="daijiao">待交{{dataAll.total_num}}张</view>
						</view>
						<view class="qianshu">{{dataAll.total_price}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="flexbetween ffffff bottombox" style="z-index: 0;">
			<view class="daijiaoje">待交金额：￥{{dataAll.total_price}}</view>
		</view>
		<u-popup round="20" :show="sxshow" @close="sxshow=false">
			<view class="mainpadding">
				<view class="flexcenter">
					<view class="titletext">筛选</view>
				</view>
				<view class="strongtext margin_top">时间</view>
				<view class="flexleft" style="flex-wrap: wrap;">
					<view class="screenbox flexcenter" v-for="(item,index) in datelist" :key="item.id"
						@click="change(item.name,index)">
						<view :class="currents == index? 'itemscreenfocus margin_top':'itemscreen margin_top'">
							{{item.name}}
						</view>
					</view>
				</view>
				<view class="strongtext margin_top">自定义时间</view>
				<view class="flexleft">
					<view class="inputscreenbox flexcenter" @click="shows=true">
						<input class="itemscreen margin_top" type="text" disabled v-model="start">
					</view>
					<view class="zwscreenbox flexcenter">
						<view class="strongtext">-</view>
					</view>
					<view class="inputscreenbox flexcenter" @click="showss=true">
						<input class="itemscreen margin_top" type="text" disabled v-model="end">
					</view>
				</view>
				<view class="flexbetween">
					<view class="surebtn reset flexcenter" style="margin-top: 60rpx;" @click="resetbtn">重置</view>
					<view class="surebtn flexcenter" style="margin-top: 60rpx;" @click="sureBtn">确认</view>
				</view>
				<!-- <view class="surebtn flexcenter" style="margin-top: 60rpx;" @click="sureBtn">确认</view> -->
			</view>
		</u-popup>
		<u-datetime-picker :show="shows" v-model="value1" mode="date" @confirm="confirm" @cancel="shows=false"
			 @close="shows=false"></u-datetime-picker>
		<u-datetime-picker :show="showss" v-model="value2" mode="date" @confirm="confirms" @cancel="showss=false"
			:minDate="mintime" @close="showss=false"></u-datetime-picker>
		<moDal :message="{modalShow:modal.modalShow,title:modal.title}" @modalSure="modalSure"></moDal><!-- 模态框 -->
	</view>
</template>

<script>
	const httpRequest = require("@/common/httpRequest.js")
	const tsc = require("@/util/ble/tsc.js");
	const esc = require("@/util/ble/esc.js");
	const encode = require("@/util/ble/encoding.js");
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				// 日期筛选
				sxshow: false,
				currents: -1,
				start: '开始时间',
				end: '结束时间',
				shows: false,
				showss: false,
				value1: Number(new Date()),
				value2: Number(new Date()),
				mintime: Number(new Date()),
				datelist: [{
						id: 1,
						name: '今日'
					},
					{
						id: 2,
						name: '昨日'
					},
					{
						id: 3,
						name: '本月'
					},
				],
				staff_id:uni.getStorageSync("user_id"),
				dataAll:{},
				// 模态框
				modal: {
					modalShow: false,
					title: "",
				},
				userInfo:{},
				// 打印机技术参数
				sendContent: "../../../static/image/news/boy.png",
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				returnResult: "",
				canvasWidth: 180,
				canvasHeight: 180,
				imageSrc: '../../static/img/abc_ic_star_black_16dp.png',
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isReceiptSend: false,
				isLabelSend: false,
				// 打印机技术结束
			}
		},
		onLoad(options) {
			this.getInfo()
		// 打印机
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
			// 打印机结束
		},
		// 打印机开始
		computed: mapState(['sysinfo', 'Bluetooth']),
		onReady() {
			let list = []
			let numList = []
			let j = 0
			for (let i = 20; i < 200; i += 10) {
				list[j] = i;
				j++
			}
			for (let i = 1; i < 10; i++) {
				numList[i - 1] = i
			}
			this.buffSize = list;
			this.oneTimeData = list[0];
			this.printNum = numList;
			this.printerNum = numList[0];
		},
		onUnload() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
		},
		// 打印机结束
		onShow() {
			this.init()
			// 打印机开始
			let that = this;
			let width;
			let height;
			uni.getImageInfo({
				src: that.imageSrc,
				success(res) {
					console.log(res.width)
					console.log(res.height)
					width = res.width
					height = res.height
					that.canvasWidth = res.width;
					that.canvasHeight = res.height;
				}
			})
			const ctx = uni.createCanvasContext("edit_area_canvas", this);
			ctx.drawImage(this.imageSrc, 0, 0, width, height);
			ctx.draw();
			// 打印机结束
		},
		methods: {
			getInfo() {
				httpRequest.request('/dhtapi/user/index', 'POST', {}).then(res => {
					this.$store.state.userInfo = res.data
					this.userInfo = res.data
				}).catch(err => {
					httpRequest.toast(err.msg)
				})
			},
			// 打印机开始
			receiptTest() {
				// this.selectshow = false
				var that = this;
				var canvasWidth = that.canvasWidth
				var canvasHeight = that.canvasHeight
				var command = esc.jpPrinter.createNew()
				command.init()
				// 标题
				command.bold(1); //加粗
				command.setFontSize(16); //字体大小
				command.setSelectJustification(1) //居中0左对齐1居中对齐2右对齐
				command.rowSpace(100);
				command.setText("货款对账单");
				command.setPrint();
				command.rowSpace(60); //行间距
				command.bold(0); //取消加粗
				command.setFontSize(0); //正常字体
				// 内容
				command.bold(0); //加粗
				command.setSelectJustification(0) //居中0左对齐1居中对齐2右对齐
				command.setText("打印时间：" + httpRequest.timereturn(Number(new Date())));
				command.setPrint();
				let time = this.start == "开始时间" ? "无" : that.start+"-"+that.end
				command.setText("筛选时间：" + time);
				command.setPrint();
				command.setText("员工：" + that.userInfo.username+"（"+that.userInfo.mobile+"）");
				command.setPrint();
				command.setText("销售：" + that.dataAll.sale_total_num+"张，"+that.dataAll.sale_total_price+"元");
				command.setPrint();
				command.setText("收欠款：" + that.dataAll.sqk_total_num+"张，"+that.dataAll.sqk_total_price+"元");
				command.setPrint();
				command.setText("预收款：" + that.dataAll.ysk_total_num+"张，"+that.dataAll.ysk_total_price+"元");
				command.setPrint();
				command.setText("合计：" + that.dataAll.total_num+"张，"+that.dataAll.total_price+"元");
				command.setPrint();
				command.setSelectJustification(1) //居中0左对齐1居中对齐2右对齐
				command.setText("询博技术支持");
				command.setPrintAndFeedRow(3);
				that.isReceiptSend = true;
				that.prepareSend(command.getData());
			},
			
			//准备发送，根据每次发送字节数来处理分包数量
			prepareSend(buff) {
				console.log(buff);
				let that = this
				let time = that.oneTimeData
				let looptime = parseInt(buff.length / time);
				let lastData = parseInt(buff.length % time);
				console.log(looptime + "---" + lastData)
				this.looptime = looptime + 1;
				this.lastData = lastData;
				this.currentTime = 1;
				that.Send(buff)
			},
			//分包发送
			Send(buff) {
				let that = this
				let {
					currentTime,
					looptime: loopTime,
					lastData,
					oneTimeData: onTimeData,
					printerNum: printNum,
					currentPrint
				} = that;
				let buf;
				let dataView;
				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData)
					dataView = new DataView(buf)
					for (var i = 0; i < onTimeData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (var i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				}
				console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
				let {
					BLEInformation
				} = that.Bluetooth;
			
				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: BLEInformation.deviceId,
					serviceId: BLEInformation.writeServiceId,
					characteristicId: BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						console.log(res)
					},
					fail: function(e) {
						console.log(e)
					},
					complete: function() {
						currentTime++
						if (currentTime <= loopTime) {
							that.currentTime = currentTime;
							that.Send(buff)
						} else {
							//  uni.showToast({
							// title: '已打印第' + currentPrint + '张',
							//  })
							if (currentPrint == printNum) {
								that.looptime = 0;
								that.lastData = 0;
								that.currentTime = 1;
								that.isReceiptSend = false;
								that.isLabelSend = false;
								that.currentPrint = 1;
							} else {
								currentPrint++;
								that.currentPrint = currentPrint;
								that.currentTime = 1;
								that.Send(buff)
							}
						}
					}
				})
			},
			// 打印机结束
			init() {
				httpRequest.request('/dhtapi/user/skDz', 'POST', {
					start_time: this.start == "开始时间" ? "" : this.start,
					end_time: this.end == "结束时间" ? "" : this.end,
					staff_id: this.staff_id
				}).then(res => {
					if (res.code == 1) {
						this.dataAll = res.data
					} else {
						httpRequest.toast(res.msg)
					}
				}).catch(err => {
					httpRequest.toast(err.msg)
				})
			},
			selectRole(url) {
				uni.navigateTo({
					url
				})
			},
			startPrint(qxpdid) {
				if (!httpRequest.qxpd(qxpdid, this.$store.state.userInfo.ability_rule_ids)) {
					return false
				}
				let that = this
				uni.showActionSheet({
					itemList: ['云打印机', '蓝牙打印机'],
					success: function(res) {
						// 选择云打印机走0
						if (res.tapIndex == 0) {
							that.modal.title = "请再次确认打印！"
							that.modalSure()
						}
						// 选择蓝牙打印机走1
						if (res.tapIndex == 1) {
							that.receiptTest()
						}
					},
					fail: function(res) {}
				});
			},
			modalSure(){
				this.modal.modalShow = false
				if(this.modal.title=="请再次确认打印！"){
					uni.showLoading({
						mask:true,
						title:"发送数据中"
					})
					let url = "/dhtapi/user/dySkDz"
					httpRequest.request(url, 'GET', {
						start_time: this.start == "开始时间" ? "" : this.start,
						end_time: this.end == "结束时间" ? "" : this.end,
						staff_id: this.staff_id
					}, false, false, true).then(res => {
						uni.hideLoading()
						httpRequest.toast(res.msg)
					}).catch(err => {
						httpRequest.toast(err.msg);
					})
				}
			},
			confirm(e) {
				console.log(e);
				this.shows = false;
				this.show = true;
				this.end = '结束时间';
				this.mintime = e.value;
				this.start = this.date(e.value);
				this.currents = -1;
			},
			confirms(e) {
				this.showss = false;
				this.show = true;
				this.maxtime = e.value;
				this.end = this.date(e.value);
				this.currents = -1;
			},
			date(timer) {
				var date = new Date(timer); //当前时间
				var year = date.getFullYear() //返回指定日期的年份
				var month = repair(date.getMonth() + 1); //月
				var day = repair(date.getDate()); //日
				var curTime = year + "-" + month + "-" + day

				function repair(i) {
					if (i >= 0 && i <= 9) {
						return "0" + i;
					} else {
						return i;
					}
				}
				return curTime
			},
			change(name, index) {
				if (name == "今日") {
					this.start = this.riqi(0);
					this.end = this.riqi(0);
				} else if (name == "昨日") {
					this.start = this.riqi(-1);
					this.end = this.riqi(-1);
				} else if (name == "本月") {
					this.start = this.benyue();
					this.end = this.riqi(0);
				}
				this.currents = index;
			},
			// 昨天“-1”今天“0”明天“1”
			riqi(day) {
				let dd = new Date();
				dd.setDate(dd.getDate() + day);
				let y = dd.getFullYear();
				let m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
				let d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
				return y + "-" + m + "-" + d;
			},
			// 本月第一天
			benyue() {
				let y = new Date().getFullYear(); //获取年份
				let m = new Date().getMonth() + 1; //获取月份
				let d = '01'
				m = m < 10 ? '0' + m : m; //月份补 0
				return [y, m, d].join("-")
			},
			sureBtn() {
				this.sxshow = false
				this.init()
			},
			// 重置
			resetbtn() {
				this.currents = -1
				this.start = "开始时间"
				this.end = "结束时间"
				this.init()
				this.sxshow = false
			},
			//跳转收款详情
			xiaoshousk(value) {
				let data = {
					type: value,
					listid: this.staff_id,
					name:""
				}
				uni.navigateTo({
					url: '/pages/workbench/caiwu/shoukuanxq?msg=' + encodeURIComponent(JSON.stringify(data))
				})
			},
			//跳转收账详情
			shouzhangls(qxpdid) {
				if (!httpRequest.qxpd(qxpdid, this.$store.state.userInfo.ability_rule_ids)) {
					return false
				}
				uni.navigateTo({
					url: '/pages/workbench/caiwu/shoukuandzls'
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.bottombox {
		padding: 38rpx 30rpx 80rpx;
		position: fixed;
		width: 100%;
		bottom: 0;
		left: 0;
		box-sizing: border-box;
	}

	.daijiaoje {
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #0BBDCB;
	}

	.shangjiaobtn {
		background: #00B855;
		border-radius: 41rpx 41rpx 41rpx 41rpx;
		padding: 12rpx 44rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
	}

	.duiztitle {
		font-size: 24rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #666666;
	}

	.bgcs {
		padding-bottom: 200rpx;
	}

	.dingdqian {
		margin-left: 156rpx;
	}

	.box3 {
		margin-bottom: 16rpx;
	}

	.box2 {
		margin: 22rpx 0 16rpx;
	}

	.righticon2 {
		width: 13rpx;
		height: 20rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.alltext {
		width: 330rpx;
		font-size: 24rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #999999;
	}

	.qianshu {
		font-size: 28rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #0BBDCB;
	}

	.daijiao {
		font-size: 22rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #F3AD3D;
		margin-left: 40rpx;
	}

	.xiaoshou {
		font-size: 28rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #000000;
	}

	.shoukuaant {
		padding: 30rpx 30rpx 20rpx;
		border-bottom: 1rpx solid rgba(0, 0, 0, .02);
	}

	.img {
		width: 40rpx;
		height: 40rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.oneimg {
		margin-right: 12rpx;
	}

	// tab切换
	.selectbox {
		padding: 6rpx 30rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #0BBDCB;
		line-height: 33rpx;
		background-color: #e1f4f5;
		border-radius: 30rpx;
		margin-right: 30rpx;
	}

	.noselectbox {
		padding: 6rpx 30rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Bold, PingFang SC;
		font-weight: bold;
		color: #999999;
		line-height: 33rpx;
		background-color: #eff0f0;
		border-radius: 30rpx;
		margin-right: 30rpx;
	}

	.selecttimetext {
		font-size: 24rpx;
		font-family: San Francisco Display-Medium, San Francisco Display;
		font-weight: 500;
		color: #666666;
		line-height: 24rpx;
	}

	.yuangbox {
		display: flex;
		align-items: center;
	}

	.ygbtn {
		margin: 16rpx 0 22rpx;
		background: rgba(153, 153, 153, .1);
		border-radius: 50rpx 50rpx 50rpx 50rpx;
		padding: 14rpx 120rpx;
		font-size: 24rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #999999;
	}

	.ygtext {
		color: #666;
		font-weight: bold;
		font-size: 32rpx
	}

	.screenbox {
		width: 33.33%;
	}

	.itemscreenfocus {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 50rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #0BBDCB;
		background-color: #e7f9fa;
	}

	.inputscreenbox {
		width: 40%;

		input {
			width: 100%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			border-radius: 50rpx;
			font-size: 28rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #333;
			background-color: #f7f9fa;
		}
	}

	.itemscreen {
		width: 200rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 50rpx;
		font-size: 28rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
		color: #999999;
		background-color: #f7f9fa;
	}

	.zwscreenbox {
		width: 20%;
		line-height: 80rpx;
	}

	// 选择框
	.itemscreens {
		padding-bottom: 20rpx;
	}

	.rightscreen {
		width: 100%;
	}

	.right {
		width: 100%;
	}

	.minwidth {
		min-width: 130rpx;
	}

	.surebtn {
		width: 45%;
	}

	.reset {
		background: #ebb563;
	}

	.allbtn {
		width: 350rpx;
		height: 52rpx;
		border-radius: 50rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 500;
	}

	.lansebtn {
		color: #0BBDCB;
		background: rgba(11, 189, 203, .1);
	}

	.huisebtn {
		color: #999999;
		background: rgba(153, 153, 153, .1);
	}
</style>
